﻿using System;
using System.Collections.Generic;
using System.Threading;
using System.Web.Mvc;
using iArtis.Extensions;

namespace iArtis.Models.Localization
{
	public abstract class LocalizedControllerBase : Controller
	{
		public String LanguageCode { get; private set; }
        public static String prevController { get; private set; }
        public static String prevAction { get; private set; }
        public static String prevId { get; private set; }

		protected override void Execute(System.Web.Routing.RequestContext requestContext)
		{
            if (requestContext.RouteData.Values.ContainsKey("languageCode"))
            {
                LanguageCode = requestContext.RouteData.Values["languageCode"].ToString();

                if (!AppConfig.SupportedLanguages.Contains(LanguageCode))
                    LanguageCode = AppConfig.DefaultLanguageCode;

                System.Globalization.CultureInfo culture = System.Globalization.CultureInfo.CreateSpecificCulture(LanguageCode);
                Thread.CurrentThread.CurrentCulture = culture;
                Thread.CurrentThread.CurrentUICulture = culture;
            }

            if (requestContext.RouteData.Values["action"].ToString() != "CurrentTab")
            {
                if (requestContext.RouteData.Values["controller"].ToString() != "Language")
                {
                    prevController = requestContext.RouteData.Values["controller"].ToString();
                    prevAction = requestContext.RouteData.Values["action"].ToString();
                    prevId = requestContext.RouteData.Values["id"].ToString();
                }
                else
                {
                    string newURL = AppExtensions.AppPath() + "/" + requestContext.RouteData.Values["id"];
                    if (prevController != null) newURL += "/" + prevController;
                    if (prevAction != null) newURL += "/" + prevAction;
                    if (prevId != null) newURL += "/" + prevId;
                    requestContext.RouteData.Values["id"] = newURL;
                }
            }
            base.Execute(requestContext);
		}
	}
}